package juc.juccore.atomic;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 演示AtomicIntegerFieldUpdate的用法
 */
public class AtomicIntegerFieldUpdateDemo implements Runnable {
    static Candidate tom;
    static Candidate tony;
    public static AtomicIntegerFieldUpdater<Candidate> scoreUpdate =
            AtomicIntegerFieldUpdater.newUpdater(Candidate.class, "score");

    public static void main(String[] args) throws InterruptedException {
        tony = new Candidate();
        tom = new Candidate();
        AtomicIntegerFieldUpdateDemo atomicIntegerFieldUpdateDemo = new AtomicIntegerFieldUpdateDemo();
        Thread t1 = new Thread(atomicIntegerFieldUpdateDemo);
        Thread t2 = new Thread(atomicIntegerFieldUpdateDemo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("普通的变量" + tom.score);
        System.out.println("升级的变量" + tony.score);

    }

    @Override
    public void run() {
        for (int i = 0; i < 10000; i++) {
            tom.score++;
            scoreUpdate.getAndIncrement(tony);
        }
    }


    public static class Candidate {
        volatile int score;
    }
}
